﻿using DimensionsHelper.Common.Contracts.TableFormatter;

namespace DimensionsHelper.Client.WinUi.ViewModels;

public partial class TableFormatterSubFileViewModel : FileViewModel
{
    private bool _updatingInternal;

    public TableFormatterSubFileViewModel()
    {
        InsertPosition = "";
        IsInsertFile = true;
        ReplaceByName = true;
    }


    [ObservableProperty]
    public partial bool IsInsertFile
    {
        get;
        set;
    }


    [ObservableProperty]
    public partial string InsertPosition
    {
        get;
        set;
    }


    [ObservableProperty]
    public partial bool ReplaceByName
    {
        get;
        set;
    }


    [ObservableProperty]
    public partial bool ReplaceByIndex
    {
        get;
        set;
    }


    partial void OnReplaceByIndexChanged(bool value)
    {
        if (_updatingInternal)
        {
            return;
        }

        _updatingInternal = true;
        ReplaceByName = !value;
        _updatingInternal = false;
    }


    partial void OnReplaceByNameChanged(bool value)
    {
        if (_updatingInternal)
        {
            return;
        }

        _updatingInternal = true;
        ReplaceByIndex = !value;
        _updatingInternal = false;
    }


    public TableInsertFileInfo GetInsertFileInfo()
    {
        if (!IsInsertFile || string.IsNullOrEmpty(InsertPosition))
        {
            return TableInsertFileInfo.Empty;
        }

        int? lineNumber = null;
        string? tableName = null;

        if (int.TryParse(InsertPosition, out int pos))
        {
            lineNumber = pos;
        }
        else
        {
            tableName = InsertPosition;
        }

        return new TableInsertFileInfo
        {
            FileName = FileName,
            LineNumber = lineNumber,
            TableName = tableName
        };
    }


    public TableReplaceFileInfo GetReplaceFileInfo()
    {
        if (IsInsertFile)
        {
            return TableReplaceFileInfo.Empty;
        }

        return new TableReplaceFileInfo
        {
            FileName = FileName,
            ByName = ReplaceByName,
            ByIndex = ReplaceByIndex
        };
    }
}